package br.com.wss.recursos;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;

public class FindDataCurso {
	private String sumario;
	private String url;
	private String curso;
	private String diretorio;
	private ManagerFile managerFile;
	private File file;
	
	public FindDataCurso(String url, Context context, String sumario) {
		this.sumario = sumario;
		this.url = url;
		
		String[] vet = url.split("/");
		diretorio = vet[vet.length - 2];
		curso = vet[vet.length - 1];
		
		File fileDir = context.getDir(diretorio, Context.MODE_PRIVATE);
		this.file = new File(fileDir, curso+".utf");
		managerFile = new ManagerFile(file);
	}
	
	public Map<String, ArrayList<String>> find() {
		if(file.exists()){
			return managerFile.readFileMap(file);
		}else{
			return findTextIntoWeb();
		}
	}

	public Map<String, ArrayList<String>> findTextIntoWeb() {
		HtmlToPlainText formatter = new HtmlToPlainText(url);
		ArrayList<String> listSumario = new ArrayList<String>();
        ArrayList<String> listText = new ArrayList<String>();
		String plainText = formatter.getText("parent-fieldname-text");
		if(plainText == null){
			return null;
		}
		
		String sum = formatter.getTextSumario();
		
        String[] vetorSumario = sum.split("\n");
        listSumario.addAll(Arrays.asList(vetorSumario));

        String[] text = plainText.split("\n");
        listText.addAll(Arrays.asList(text));

        for (String string : listSumario) {
			listText.remove(string);
		}
        
		
        Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        listSumario.remove(0);
        map.put(sumario, listSumario);
        
        for (int i = 0; i < listSumario.size(); i++) {
            ArrayList<String> listConteudo = new ArrayList<String>();
            String indice = listSumario.get(i);
            boolean cond = true;
            while ((cond) && (!listText.isEmpty())) {
                String ind = listText.remove(0);
                if (!ind.equalsIgnoreCase("Topo")) {
                    listConteudo.add(ind);
                    cond = true;
                
                }else{
                	cond = false;
                }
                System.out.println("Cond = "+cond);
            }
            map.put(indice, listConteudo);
        }
		saveFile(map);
		return map;
	}
	
	public void saveFile(Map<String, ArrayList<String>> map) {
		managerFile.writeFile(map);
	}
}
